<?php

/**
 * gov_organization actions.
 *
 * @package    erp-dnict
 * @subpackage gov_organization
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class gov_organizationActions extends sfActions
{
 /**
  * Executes index action
  *
  * @param sfRequest $request A request object
  */
  public function executeIndex(sfWebRequest $request)
  {
  	$q = Doctrine_Query::create()
            ->from('GovOrganization go')
            ->addWhere('go.is_active = ?', true);

    $this->gov_organizations = $q->execute();
    return sfView::SUCCESS;
  }

  public function executeEdit(sfWebRequest $request)
  {
    $this->gov_organization_id = $request->getParameter('id', null);
    $this->form = new GovOrganizationForm();

    if ($this->gov_organization_id) {
      $gov_organization = Doctrine_Core::getTable('GovOrganization')->find($this->gov_organization_id);
      $this->form = new GovOrganizationForm($gov_organization);
    }

    if ($request->isMethod('post')) {
      $form_data = $request->getParameter('gov_organization');
      $this->form->bind($form_data);
      if ($this->form->isValid()) {
        if (!$request->getParameter('id'))
          $gov_organization = $this->form->save();
        else { // update
          $gov_organization = Doctrine_Core::getTable('GovOrganization')->find($request->getParameter('id'));
          if ($gov_organization) {
            $gov_organization->name = $form_data['name'];
            $gov_organization->description = $form_data['description'];
            $gov_organization->is_active = $form_data['is_active'] == 'on' ? true : false;
            $gov_organization->parent_id = $form_data['parent_id'];
            $gov_organization->save();
          }
        }
        $this->redirect('@gov_organization_index');
      }
    }
    return sfView::SUCCESS;
  }

  public function executeRemove(sfWebRequest $request)
  {
    $gov_organization_id = $request->getParameter('id', null);
    if ($gov_organization_id) {
      $gov_organization = Doctrine_Core::getTable('GovOrganization')->find($gov_organization_id);
      if ($gov_organization) {
        foreach ($gov_organization->Profiles as $profile) {
          $profile->gov_organization_id = 0;
          $profile->save();
        }

        $children = Doctrine_Core::getTable('GovOrganization')->findByParentId($gov_organization->id);
        if ($children)
        	foreach ($children as $child) {
        		$child->parent_id = $gov_organization->parent_id;
        		$child->save();
        	}
        $gov_organization->is_active = false;
        $gov_organization->save();
      }
    }
    $this->redirect('@gov_organization_index');
  }
}
